package example.file;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.junit.Test;

import java.io.File;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class FileDuplicateTest {

    @Test
    public void findDuplicateFiles() {
        String targetDirectory = "F:\\"; // 替换为您要搜索的目录
        Map<String, String> fileNameToPathMap = new HashMap<>();
        String[] excludedExtensions = {".xml", ".java", ".yml", ".js", ".css", ".yaml", ".json", ".bpmn", ".md",
                ".gif", ".png", ".png", ".sql", ".jar", ".c", ".scss", ".txt", "cover.jpg", ".svn-base", "Makefile",
                ".scssc", ".project", ".properties", ".jsdtscope", ".classpath"
        }; // 要排除的后缀
        HashMap<String, String> map = new HashMap<>();

        StopWatch stopWatch = new StopWatch();
        try {
            stopWatch.start();

            Collection<File> files = FileUtils.listFiles(new File(targetDirectory), null, true);
            stopWatch.stop();

            long watchTime = stopWatch.getTime(TimeUnit.MILLISECONDS);
            System.out.printf("watchTime=%s\n", watchTime);

            for (File file : files) {
                String fileName = file.getName();
                if (fileName.contains(":\\$RECYCLE.BIN")) continue;
                if (shouldExcludeFile(fileName, excludedExtensions)) {
                    // 文件名符合要排除的后缀，跳过
                    continue;
                }

                if (fileNameToPathMap.containsKey(fileName)) {
                    // 文件名已存在，打印重复文件的完整路径
                    //System.out.println("Duplicate File: " + fileName);
                    //System.out.println("Path 1: " + fileNameToPathMap.get(fileName));
                    //System.out.println("Path 2: " + yyds.file.getAbsolutePath());
                    String absolutePath = FileUtils.getFile(fileNameToPathMap.get(fileName)).getParentFile().getAbsolutePath();
                    String absolutePath1 = file.getParentFile().getAbsolutePath();
                    map.put(absolutePath1, absolutePath);

                } else {
                    fileNameToPathMap.put(fileName, file.getAbsolutePath());
                }
            }
            //
            Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> next = iterator.next();
                System.out.println(next.getKey() + "\n" + next.getValue() + "\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean shouldExcludeFile(String fileName, String[] excludedExtensions) {
        for (String extension : excludedExtensions) {
            if (fileName.endsWith(extension)) {
                return true;
            }
        }
        return false;
    }
}
